import { SEO } from '@/utils/seo'
import { request } from '@umijs/max'
import { message, Progress } from 'antd'
import * as PANOLENS from 'panolens'
import { useEffect, useRef, useState } from 'react'
import styles from './index.less'

// 使用相同的远程全景图 URL
const REMOTE_PANO_URL = `${TENCENT_OSS_URL}/dji_fly_20250131_142248_0066_1738305921186_pano.min.jpg`

const Lab = () => {
  const containerRef = useRef<HTMLDivElement>(null)
  const [downloadProgress, setDownloadProgress] = useState<number>(0)
  const [isDownloading, setIsDownloading] = useState<boolean>(false)
  const viewerRef = useRef<any>(null)
  const panoramaRef = useRef<any>(null)

  // 下载图片
  const downloadImage = async (url: string): Promise<string> => {
    setIsDownloading(true)
    setDownloadProgress(0)

    try {
      const response = await request(url, {
        method: 'GET',
        responseType: 'blob',
        getResponse: true,
        onDownloadProgress: (progressEvent) => {
          if (progressEvent.total) {
            const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100)
            setDownloadProgress(percent)
          }
        }
      })

      const blob = response.data
      const localUrl = URL.createObjectURL(blob)
      setIsDownloading(false)
      return localUrl
    } catch (error) {
      setIsDownloading(false)
      message.error('全景图下载失败')
      throw error
    }
  }

  // 初始化全景图
  useEffect(() => {
    if (!containerRef.current) return

    const initPanorama = async () => {
      try {
        // 下载远程图片
        const localUrl = await downloadImage(REMOTE_PANO_URL)

        // 创建全景图
        const panorama = new PANOLENS.ImagePanorama(localUrl)
        panoramaRef.current = panorama

        // 创建查看器
        const viewer = new PANOLENS.Viewer({
          container: containerRef.current,
          autoRotate: true,
          autoRotateSpeed: 0.5,
          controlBar: true
          // 太灵敏了
        })
        viewerRef.current = viewer

        // 添加全景图到查看器
        viewer.add(panorama)
      } catch (error) {
        message.error('初始化全景图失败')
      }
    }

    initPanorama()

    // 清理函数
    return () => {
      if (viewerRef.current) {
        viewerRef.current.dispose()
      }
    }
  }, [])

  return (
    <>
      <SEO
        title="实验室 - Zusheng Studio"
        description="Zusheng Studio的实验室，用于研究和展示各种前沿技术和创意实验。"
        keywords="Zusheng,实验室,技术研究,创意实验,Panolens.js,全景图"
        url="https://zusheng.cc/lab"
      />
      <div className={styles.pagePanorama + ' page'}>
        <div ref={containerRef} className={styles.container}>
          {isDownloading && (
            <div className={styles.loadingContainer}>
              <Progress
                type="circle"
                percent={downloadProgress}
                size={'small'}
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068'
                }}
                format={(percent) => `${percent}%`}
              />
            </div>
          )}
        </div>
      </div>
    </>
  )
}

export default Lab
